﻿Imports System.IO
Imports System.Text
Imports System.Threading
Imports System.Configuration
Imports System.windows.forms
Imports System.Collections.Specialized

''' <summary>
''' Classe reponsavel pro fazer as atualizações dos arquivos da aplicacao
''' </summary>
''' <remarks></remarks>
Public Class DownloadManager

#Region "Declaração de constantes"
    Private Const FILE_UPDATE As String = "UPDATER.DLL"
    Private Const APP_DOMAIN_NAME As String = "DOMAINAPPLICATION"
#End Region

#Region "Declaração de campos privados"
    Private Shared fblnRequiredDownloadExecutable As Boolean
    Private Shared alertUpdate As Boolean = False
    'Private Shared _assemblyController As AssemblyCore
    'Private Shared _appDomainController As ApplicationDomain
#End Region

#Region "Declaração de propriedades publicas"
    Public Shared ReadOnly Property RequireDownloadExecutable() As Boolean
        Get
            Return (fblnRequiredDownloadExecutable)
        End Get
    End Property
#End Region

#Region "Declaração de métodos publicos"

    Public Shared Sub RemoveUpdatedFiles()
        Try
            ' remove arquivos renoeados
            Dim strFiles() As String
            strFiles = Directory.GetFiles(".", "*.removed")
            For Each strFile As String In strFiles
                File.Delete(strFile)
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message,
                            "Courier - Módulo Inicial.",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error)
        End Try
    End Sub

    'Public Shared Function CheckForUpdates(ByVal informarReinicializacao As Boolean) As Boolean
    '    Return UpdateComponents(informarReinicializacao)
    'End Function

    Public Shared Function UpdateComponents(ByVal sNomePastaModulo As String, ByVal sPastaVersao As String, Optional ByVal informarReinicializacao As Boolean = False) As Boolean
        RemoveUpdatedFiles()
        Try
            Dim strDiretorioServer As String = "\\172.16.2.75\Courier$\Update\" & sNomePastaModulo & "\" & sPastaVersao

            Dim fileNew As Boolean
            Dim strFilesServer() As String = Directory.GetFileSystemEntries(strDiretorioServer)
            Dim strDiretorioApp As String = "c:/Courier/" & sNomePastaModulo


            'Dim strDiretorioApp As String = Directory.GetCurrentDirectory()
            Dim strFilesCliente() As String = Directory.GetFileSystemEntries(strDiretorioApp)
            Dim strFileSrv As String = String.Empty
            Dim strFileCli As String = String.Empty
            Dim strFileFullPathCliente As String = String.Empty

            For Each strFileFullPathServer As String In strFilesServer

                fileNew = True

                strFileSrv = strFileFullPathServer.Substring(strFileFullPathServer.LastIndexOf("\") + 1)
                For i As Integer = 0 To strFilesCliente.Length - 1
                    strFileFullPathCliente = strFilesCliente(i)
                    strFileCli = strFileFullPathCliente.Substring(strFileFullPathCliente.LastIndexOf("\") + 1)
                    If (strFileSrv.ToUpper() = strFileCli.ToUpper()) Then
                        fileNew = False
                        If (Not FileUtil.IsDirectory(strFileFullPathServer)) Then
                            If (FileUtil.FileServerIsNew(strFileFullPathServer, strFileFullPathCliente)) Then
                                fblnRequiredDownloadExecutable = True
                                'Remove arquivos ".removed" caso existam.
                                FileUtil.DeleteFile(strFileFullPathCliente & ".removed")
                                ' renomeia o arquivo antes de atualizar
                                FileSystem.Rename(strFileFullPathCliente, strFileFullPathCliente & ".removed")
                                ' salvando o novo arquivo na maquina do cliente
                                File.Copy(strFileFullPathServer, strFileFullPathCliente)
                            End If
                        End If
                        Exit For
                    ElseIf i = strFilesCliente.Length - 1 Then
                        If (Not FileUtil.IsDirectory(strFileFullPathServer)) Then
                            fileNew = True
                        Else
                            fileNew = False
                        End If
                    End If
                Next
                If fileNew Then
                    If Not FileUtil.IsDirectory(strFileFullPathServer) Then
                        'File.Copy(strFileFullPathServer, strDiretorioApp & "\" & strFileSrv)
                        File.Copy(strFileFullPathServer, strDiretorioApp & "/" & strFileSrv)
                    End If
                End If
            Next

            If (fblnRequiredDownloadExecutable) Then
                fblnRequiredDownloadExecutable = False
                If informarReinicializacao Then
                    Dim myThreadDelegate As New ThreadStart(AddressOf RestartApplication)
                    Dim myThread As New Thread(myThreadDelegate)
                    myThread.SetApartmentState(ApartmentState.STA)
                    myThread.Start()
                    RestartApplicationSemSleep()
                    'Else
                    'MessageBox.Show("Os Módulos foram atualizados com sucesso e o mesmo será reinicializado!", _
                    '            "Sistema Courier.", _
                    '            MessageBoxButtons.OK, _
                    '            MessageBoxIcon.Information)
                    'RestartApplicationSemSleep()
                End If
            End If
        Catch ex As Exception
            Throw New Exception("Problema durante a atualização do Sistema Courier. Verifique com o setor de T.I." & _
                                Environment.NewLine & Environment.NewLine & _
                                ex.Message & _
                                Environment.NewLine & Environment.NewLine & _
                                ex.StackTrace)
        End Try
    End Function

    Public Shared Function ExisteAtualizacao() As Boolean
        RemoveUpdatedFiles()
        Try
            Dim strDiretorioServer As String = "//172.16.2.75/Update/"
            Dim strFilesServer() As String = Directory.GetFileSystemEntries(strDiretorioServer)
            Dim strDiretorioApp As String = Directory.GetCurrentDirectory()
            Dim strFilesCliente() As String = Directory.GetFileSystemEntries(strDiretorioApp)
            Dim strFileSrv As String = String.Empty
            Dim strFileCli As String = String.Empty
            Dim strFileFullPathCliente As String = String.Empty

            For Each strFileFullPathServer As String In strFilesServer
                strFileSrv = strFileFullPathServer.Substring(strFileFullPathServer.LastIndexOf("\") + 1)
                For i As Integer = 0 To strFilesCliente.Length - 1
                    strFileFullPathCliente = strFilesCliente(i)
                    strFileCli = strFileFullPathCliente.Substring(strFileFullPathCliente.LastIndexOf("\") + 1)
                    If strFileSrv.ToUpper() = strFileCli.ToUpper() Then
                        If FileUtil.FileServerIsNew(strFileFullPathServer, strFileFullPathCliente) Then
                            Return True
                        End If
                        Exit For
                    End If
                Next
            Next
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function

#End Region

#Region "Declaração de métodos privados"

    Private Shared Sub RestartApplication()
        Thread.Sleep(4000)
        Dim objProcess As Process = Process.GetCurrentProcess()
        Process.Start(AppDomain.CurrentDomain.FriendlyName)
        objProcess.Kill()
    End Sub

    Private Shared Sub RestartApplicationSemSleep()
        Dim objProcess As Process = Process.GetCurrentProcess()
        Process.Start(AppDomain.CurrentDomain.FriendlyName)
        objProcess.Kill()
    End Sub

    Private Shared Function IsExecutableSystem(ByVal strFileName As String) As Boolean
        Dim flI As New FileInfo(strFileName)
        If strFileName.ToUpper() = FILE_UPDATE Then
            Return True
        ElseIf flI.Extension.ToUpper() = "EXE" OrElse flI.Extension.ToUpper() = "CONFIG" Then
            Return True
        End If
        Return False

    End Function

#End Region

End Class